import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:rss_readneed/punch_card/punchCardModel.dart';

typedef MsgCallback = void Function(String msg);

class SNAccount {

  final String account; //账号
  final String password; //密码
  bool  isSnPageFirst;//是否优先展示sn简洁页面

  bool isFatch = false;

  SNAccount({

    this.account,
    this.password,
  });

  //实例对象属性赋值
  SNAccount.fromJson(Map json)
      : account = json["account"],
        password = json["password"],
        isSnPageFirst = json["isSnPageFirst"]
        ;

//encode会自动执行model 里面的toJson
  Map toJson() =>
      {
        "account": account,
        "password": password,
        "isSnPageFirst":isSnPageFirst
      };


  //用户信息
  static SNAccount _instance;
  static SNAccount get instance {

    if (_instance == null) {

      _instance = SNAccount();

      SNAccount().getSNAccount().then((SNAccount model){

        _instance = model;

        //初始化成功拉取数据
        if (_instance.account !=null && _instance.account.length >0 && _instance.password !=null && _instance.password.length >0) {

//          SNAccount().fetchListDatas(_instance.account, _instance.password,(msg){},false);
        }
      });
    }
    return _instance;
  }

  static void get refreshInstance {

    SNAccount().getSNAccount().then((SNAccount model){

      bool isFatch = _instance.isFatch;
      _instance = model;
      _instance.isFatch = isFatch;//isFatch状态做延续
      //通知这个月发生更改
      SNAccount.noti.sink.add(_instance.isSnPageFirst);
    });
  }

  //通知更改 - 切换主页面
  static StreamController _noti;
  static StreamController get noti {

    if (_noti == null) {

      _noti = StreamController.broadcast();
    }

    return _noti;
  }

//所有数据
  Future<void> save(String account,String password,bool isFirstPage) async {

      SharedPreferences prefs = await SharedPreferences.getInstance();

      prefs.setString("sn_account_in", json.encode({"account":account,"password":password,"isSnPageFirst":isFirstPage}));

      SNAccount.refreshInstance;
  }

  Future<SNAccount> getSNAccount() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    String string = prefs.getString("sn_account_in");

    if (string == null || string.length == 0) { //如果不存在就返回空数组

      return SNAccount();
    }

    Map info = json.decode(string);

    return SNAccount.fromJson(info);
  }

  Future<List> fetchListDatas (String account,String cookieString,MsgCallback callBack,bool sourceLogin) async {

    List<String> checkTimes = [];

    Map<String,String> cookie = {
      "Cookie":cookieString
    };

    DateTime todayDate = PunchCardModel().todayDateTime();

    String todayString = PunchCardModel().dateTimeString(todayDate);

    String monthFirstDayString = todayString.substring(0,7) + "-01";


    while (todayString != monthFirstDayString) {

      http.Response responseDatas = await http.get("http://sdot.cnsuning.com/sdot-admin/trafficFeeCommon/getWorkTime.htm?billTime=" + todayString +" 23:59:59&applyerNo=" + account,headers: cookie);

      print(responseDatas.body);
      Map mapDatas = jsonDecode(responseDatas.body);

      String workTime = mapDatas["workTime"];
      if (workTime != null && workTime.length > 0) {

        checkTimes.add(mapDatas["workTime"]);
      }

      todayDate = todayDate.subtract(Duration(days: 1));

      todayString =  PunchCardModel().dateTimeString(todayDate);
    }

    if (checkTimes.length > 0) {

      await PunchCardModel().saveList(checkTimes);

      SNAccount.instance.isFatch = true;
    }
  }
}